package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"pic-text-mgr/cache"
	"pic-text-mgr/models"
	"strconv"
	"time"
)

func BookAdd(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	tx := models.DB.Begin()
	book := models.Book{
		Model:        gorm.Model{},
		Title:        title,
		Content:      content,
		UserId:       userId,
		User:         models.User{},
		CommentCount: 0,
	}
	err := tx.Create(&book).Error
	if err != nil {
		tx.Rollback()
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "发布失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "发布成功",
		})
		return
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var books []models.Book
	list_key := "list_key" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Int()
	if cachejson < 0 {
		models.DB.Offset(offset).Limit(size).Find(&books)
		cachedata, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, list_key, cachedata, time.Hour*2)
	}
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var book models.Book
	err := models.DB.Where("id=?", id).First(&book).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "查询成功",
		})
		return
	}
}
